using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Core.Data;
using Urs.Data.Domain.Stores;

namespace Urs.Services.Stores
{
    public partial class GoodsTagService : IGoodsTagService
    {
        #region Fields

        private readonly IRepository<GoodsTag> _goodsTagRepository;

        #endregion

        #region Ctor

        public GoodsTagService(IRepository<GoodsTag> goodsTagRepository)
        {
            _goodsTagRepository = goodsTagRepository;
        }

        #endregion

        #region Methods

        public virtual void DeleteGoodsTag(GoodsTag goodsTag)
        {
            if (goodsTag == null)
                throw new ArgumentNullException("goodsTag");

            _goodsTagRepository.Delete(goodsTag);

        }

        public virtual IList<GoodsTag> GetAllGoodsTags(bool showHidden = false)
        {
            var query = _goodsTagRepository.Table;
            if (!showHidden)
                query = query.Where(pt => pt.Count > 0);
            query = query.OrderByDescending(pt => pt.Count);
            var goodsTags = query.ToList();
            return goodsTags;
        }

        public virtual GoodsTag GetGoodsTagById(int goodsTagId)
        {
            if (goodsTagId == 0)
                return null;

            var goodsTag = _goodsTagRepository.GetById(goodsTagId);
            return goodsTag;
        }

        public virtual GoodsTag GetGoodsTagByName(string name)
        {
            var query = from pt in _goodsTagRepository.Table
                        where pt.Name == name
                        select pt;

            var goodsTag = query.FirstOrDefault();
            return goodsTag;
        }

        public virtual void InsertGoodsTag(GoodsTag goodsTag)
        {
            if (goodsTag == null)
                throw new ArgumentNullException("goodsTag");

            _goodsTagRepository.Insert(goodsTag);
        }

        public virtual void UpdateGoodsTag(GoodsTag goodsTag)
        {
            if (goodsTag == null)
                throw new ArgumentNullException("goodsTag");

            _goodsTagRepository.Update(goodsTag);

        }

        public virtual void UpdateGoodsTagTotals(GoodsTag goodsTag)
        {
            if (goodsTag == null)
                throw new ArgumentNullException("goodsTag");

            int newTotal = goodsTag.Goods
                .Where(p => !p.Goods.Deleted && p.Goods.Published)
                .Count();

            goodsTag.Count = newTotal;
            UpdateGoodsTag(goodsTag);

        }

        #endregion
    }
}
